home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / std / c++ / 880 < prev    next >
Encoding:
Internet Message Format  |  1996-08-06  |  2.3 KB

  1. From: Philippe Verdy <100105.3120@compuserve.com>
  2. Message-ID: <4jc2fa$bqu@arl-news-svc-2.compuserve.com>
  3. X-Original-Date: 27 Mar 1996 18:47:05 GMT
  4. Path: in1.uu.net!bounce-back
  5. Date: 27 Mar 96 21:41:18 GMT
  6. Approved: fjh@cs.mu.oz.au
  7. Newsgroups: comp.std.c++
  8. Subject: Re: double const declarations
  9. Organization: CompuServe Incorporated
  10. X-Auth: PGPMoose V1.1 PGP comp.std.c++
  11.     iQBFAgUBMVm2I+EDnX0m9pzZAQGy5gF/S0GJD+hXSzmJB2uFn7v6OdnfDHfDryGo
  12.     1u/ygQAqFUVtf43Iyh5GB/yJl6uxw2Ye
  13.     =9Hub
  14.  
  15. dak <pierreba@poster.cae.ca> s'icrit :
  16. > I've just encountered a problem in one of our template design and wondered
  17. > what could be done about it. It concerns const reference return value from
  18. > a templated member function, for example:
  19. > template <class T> class SmartPtr
  20. > {
  21. >     // ... whatever:
  22. > public:
  23. >     const T & Dereference ();
  24. > };
  25. > The problem arise when T is instantiated with a Container of constants:
  26. > SmartPtr<const int> a;
  27. > Here we have a double const which is not supported by the compiler, nor the
  28. > standard, I believe.  Is there a fix or should we abandon all hope of using
  29. > const returns in templates ?
  30.  
  31. Declare a temporary template<class T> to use <T> types only, but no <const T>,
  32. then create another template class that will use <const T> as the parameter
  33. of the first template.
  34. To make this class usable for const and non-const references, you can add
  35. another template parameter to the first class : one for the case T should be
  36. const, one for the other case.
  37. Example:
  38.  
  39. template <class T, class CT>
  40. class SmartPtr2  {
  41.    SmartPtr2(T* p) { mp = const_cast<CT>(p) ; }
  42.    CT & Dereference() {
  43.      return *mp ;
  44.    }
  45.  private :
  46.    CT *mp ;
  47. } ;
  48. template <class T> class ConstSmartPtr : SmartPtr<T, T> {} ;
  49. template <class T> class FreeSmartPtr : SmartPtr<T, const T> {} ;
  50.  
  51. Now you can safely use:
  52.   FreeSmartPtr<const X> and ConstSmartPtr<X>.
  53.  
  54. You cannot use:
  55.   ConstSmartPtr<const X>
  56. due to the double const problem;
  57.  
  58. But you can use:
  59.   FreeSmartPtr<X>
  60. no const at all !
  61. ---
  62. [ comp.std.c++ is moderated.  To submit articles: try just posting with      ]
  63. [ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu         ]
  64. [ FAQ:      http://reality.sgi.com/employees/austern_mti/std-c++/faq.html    ]
  65. [ Policy:   http://reality.sgi.com/employees/austern_mti/std-c++/policy.html ]
  66. [ Comments? mailto:std-c++-request@ncar.ucar.edu                             ]
  67.